﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ContractManager.BLL.Business;
using ContractManager.Common.Class;
using ContractManager.Common.FormBase;
using System.Windows.Forms;
using ContractManager.Entity;
using ContractManager.Lists.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;

namespace ContractManager.Lists.Contracts
{
    public partial class FrmDocumentsDetail : XtraFormBase
    {
        #region "Private Variable"
        private readonly BackgroundWorker _loadworker = new BackgroundWorker();
        public List<InsuranceType> LstInsuranceType = new List<InsuranceType>();
        public List<Investors> LstInvestors = new List<Investors>();
        public List<DocumentTypes> LstDocumentTypes = new List<DocumentTypes>(); 

        public bool SaveClose;
        public bool SaveNew;
        public bool OnlyView;
        public int MasterId;

        
        #endregion

        #region "Form Construction"
        public FrmDocumentsDetail()
        {
            InitializeComponent();
            ClsVariable.DoubleBuffer(this);
            _loadworker.DoWork += loadworker_DoWork;
            _loadworker.RunWorkerCompleted += loadworker_RunWorkerCompleted;
        }
        #endregion

        #region "Private Method"

        private void BlankForm()
        {
            /*txtDocNoTo.EditValue = null;
            txtDocDateTo.EditValue = null;
            txtDocAddress.EditValue = null;
            txtInvID.EditValue = null;
            txtInsTypId.EditValue = null;
            txtDocNo.EditValue = null;
            txtDocNotation.EditValue = null;
            txtDocDateVb.EditValue = null;
            txtDocContent.EditValue = null;
            txtDocTypId.EditValue = null;
            txtConId.EditValue = null;
            txtConDate.EditValue = null;
            txtConName.EditValue = null;
            txtConAmount.EditValue = null;
            txtConSetAmount.EditValue = null;
            txtConSentDate.EditValue = null;
            txtConReceiptDate.EditValue = null;
            txtConDescription.EditValue = null;
            txtDocResPerson.EditValue = null;
            txtDocResContent.EditValue = null;
            txtCustomField1.EditValue = null;
            txtCustomField2.EditValue = null;
            txtCustomField3.EditValue = null;
            txtCustomField4.EditValue = null;
            txtCustomField5.EditValue = null;
            txtCustomField6.EditValue = null;
            txtCustomField7.EditValue = null;
            txtCustomField8.EditValue = null;
            txtCustomField9.EditValue = null;
            txtCustomField10.EditValue = null;*/

            this.ResetControls();
            //txtDocNoTo.Properties.ReadOnly = MasterId > 0;
            grdDetail.DataSource = ClsDocuments.ListDetail(0);
        }

        public void GetData()
        {
            if (!_loadworker.IsBusy)
            {
                _loadworker.RunWorkerAsync();
                ClsVariable.SetWaitDialogCaption(string.Format("Nạp danh sách {0}...", Text));
            }
        }

        private void LoadLookupData()
        {
            txtConId.Properties.DataSource = ClsContracts.GetLookupAll();
            txtConId.Properties.DisplayMember = "ConNo";
            txtConId.Properties.ValueMember = "ConId";

           
            txtDocTypId.Properties.DataSource = LstDocumentTypes;
            txtDocTypId.Properties.DisplayMember = "DocTypName";
            txtDocTypId.Properties.ValueMember = "DocTypId";

            EmpSearchLookUpEdit.DataSource = ClsEmployees.SelectAll();
            EmpSearchLookUpEdit.DisplayMember = "FullName";
            EmpSearchLookUpEdit.ValueMember = "ID";

            ExchangeTypeSearchLookUpEdit.DataSource = ClsExchangeType.SelectAll();
            ExchangeTypeSearchLookUpEdit.DisplayMember = "ExcName";
            ExchangeTypeSearchLookUpEdit.ValueMember = "ExcId";

            if (MasterId > 0) GetDetail();
        }

        private void GetDetail()
        {
            var detail = ClsDocuments.SelectByPk(MasterId);
            if (detail != null)
            {
                txtDocNoTo.EditValue = String.Format("{0}", detail.DocNoTo);
                txtDocDateTo.EditValue = detail.DocDateTo;
                txtDocAddress.EditValue = String.Format("{0}", detail.DocAddress);
               
                txtDocNo.EditValue = String.Format("{0}", detail.DocNo);
                txtDocNotation.EditValue = String.Format("{0}", detail.DocNotation);
                txtDocDateVb.EditValue = detail.DocDateVb;
                txtDocContent.EditValue = String.Format("{0}", detail.DocContent);
                txtDocTypId.EditValue = detail.DocTypId;

                txtConId.EditValue = detail.ConId;
                txtDocResPerson.EditValue = String.Format("{0}", detail.DocResPerson);
                txtDocResContent.EditValue = String.Format("{0}", detail.DocResContent);

                txtCustomField1.EditValue = String.Format("{0}", detail.CustomField1);
                txtCustomField2.EditValue = String.Format("{0}", detail.CustomField2);
                txtCustomField3.EditValue = String.Format("{0}", detail.CustomField3);
                txtCustomField4.EditValue = String.Format("{0}", detail.CustomField4);
                txtCustomField5.EditValue = String.Format("{0}", detail.CustomField5);
                txtCustomField6.EditValue = String.Format("{0}", detail.CustomField6);
                txtCustomField7.EditValue = String.Format("{0}", detail.CustomField7);
                txtCustomField8.EditValue = String.Format("{0}", detail.CustomField8);
                txtCustomField9.EditValue = String.Format("{0}", detail.CustomField9);
                txtCustomField10.EditValue = String.Format("{0}", detail.CustomField10);

                grdDetail.DataSource = ClsDocuments.ListDetail(MasterId);
            } 

        }

        private void DoSave()
        {
            grdDetail.EmbeddedNavigator.Buttons.DoClick(grdDetail.EmbeddedNavigator.Buttons.EndEdit);
            DataTable dtSource = (DataTable)grdDetail.DataSource;

            #region "Check Condition"
            //if (!FormIsNotValidate)
            //{
            //    if (!dxValidationProvider.Validate())
            //    {
            //        XtraMessageBox.Show(
            //                    "Vui lòng nhập đầy đủ thông tin trước khi lưu",
            //                    "Thông báo",
            //                    MessageBoxButtons.OK,
            //                    MessageBoxIcon.Error);
            //        txtCode.SelectAll();
            //        txtCode.Focus();
            //        return;
            //    }
            //}
            
            #endregion

            var item = MasterId <= 0 ? new Documents() : ClsDocuments.SelectByPk(MasterId);
            item.DocNoTo = String.Format("{0}", txtDocNoTo.EditValue);
            item.DocDateTo = txtDocDateTo.DateTime;

            item.DocAddress = String.Format("{0}", txtDocAddress.EditValue);
            //item.InvID = Convert.ToInt32(txtInvID.EditValue);
            //item.InsTypId = Convert.ToInt32(txtInsTypId.EditValue);
            item.DocNo = String.Format("{0}", txtDocNo.EditValue);
            item.DocNotation = String.Format("{0}", txtDocNotation.EditValue);
            item.DocDateVb = txtDocDateVb.DateTime;
            item.DocContent = String.Format("{0}", txtDocContent.EditValue);
            item.DocTypId = Convert.ToInt32(txtDocTypId.EditValue);
            item.ConId = Convert.ToInt32(txtConId.EditValue);

            item.DocResPerson = String.Format("{0}", txtDocResPerson.EditValue);
            item.DocResContent = String.Format("{0}", txtDocResContent.EditValue);

            item.CustomField1 = String.Format("{0}", txtCustomField1.EditValue);
            item.CustomField2 = String.Format("{0}", txtCustomField2.EditValue);
            item.CustomField3 = String.Format("{0}", txtCustomField3.EditValue);
            item.CustomField4 = String.Format("{0}", txtCustomField4.EditValue);
            item.CustomField5 = String.Format("{0}", txtCustomField5.EditValue);
            item.CustomField6 = String.Format("{0}", txtCustomField6.EditValue);
            item.CustomField7 = String.Format("{0}", txtCustomField7.EditValue);
            item.CustomField8 = String.Format("{0}", txtCustomField8.EditValue);
            item.CustomField9 = String.Format("{0}", txtCustomField9.EditValue);
            item.CustomField10 = String.Format("{0}", txtCustomField10.EditValue);

            item.FormId = FormNo;
            item.VoucherCate = VoucherCate;

            item.ListAdd = GetListAdd(dtSource.GetChanges(DataRowState.Added));
            item.ListUpdate = GetListUpdate(dtSource.GetChanges(DataRowState.Modified));
            item.ListDelete = GetListDelete(dtSource.GetChanges(DataRowState.Deleted));

            try
            {
                if (MasterId > 0)
                {
                    item.UpdateBy = ClsVariable.EmployeeId;
                    item.UpdateDate = DateTime.Now;
                    ClsDocuments.Update(item); 
                }
                else
                {
                    item.CreateBy = ClsVariable.EmployeeId;
                    item.CreateDate = DateTime.Now;
                    ClsDocuments.Insert(item);
                    MasterId = item.DocId;
                }

                
                if (SaveNew)
                {
                    MasterId = 0;
                    BlankForm();
                    txtDocNoTo.Focus();
                    
                }
                else if (SaveClose)
                {
                    Close();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(
                    String.Format("Có lỗi xảy ra trong quá trình cập nhật dữ liệu. {0}", ex.Message),
                    "Thông báo",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void DoDelete()
        {
            if (MasterId <= 0) return;
            
            try
            {
                if (
                        XtraMessageBox.Show(
                                        "Bạn có muốn xóa bản ghi này không?",
                                        "Thông báo",
                                        MessageBoxButtons.YesNo,
                                        MessageBoxIcon.Question) == DialogResult.No) return;
                ClsRevenues.DeleteByPk(MasterId);
                Close();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(
                       "Có lỗi xảy ra trong quá trình xóa dữ liệu. " + ex.Message,
                       "Thông báo",
                       MessageBoxButtons.OK,
                       MessageBoxIcon.Error);
            }
        }

        
        private void GetContractInfor(int conId)
        {
            var detail = ClsContracts.SelectByPk(conId);
            if (detail != null)
            {
                txtConDate.EditValue = detail.ConDate;
                txtConName.EditValue = String.Format("{0}", detail.ConName);
                txtConAmount.EditValue = detail.ConAmount;
                txtConSetAmount.EditValue = detail.ConSetAmount;
                txtConSentDate.EditValue = detail.ConSentDate;
                txtConReceiptDate.EditValue = detail.ConReceiptDate;
                txtConDescription.EditValue = String.Format("{0}", detail.ConDescription);

                txtInvID.EditValue = String.Format("{0}", detail.ConPartAName);
                txtInsTypId.EditValue = String.Format("{0}", detail.InsTypName);

                ContractDetailSearchLookUpEdit.DataSource = ClsContracts.ListDetail(conId);
                ContractDetailSearchLookUpEdit.ValueMember = "ConDetId";
                ContractDetailSearchLookUpEdit.DisplayMember = "ConDetContent";

            }
        }

        private List<DocumentDetails> GetListAdd(DataTable dataTable)
        {
            List<DocumentDetails> list = new List<DocumentDetails>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    DocumentDetails item = new DocumentDetails();
                    item.DocDetId = 0;
                    item.ConDetId = Convert.ToInt32(row["ConDetId"]);
                    item.DocDetContent = String.Format("{0}", row["DocDetContent"]);
                    if (!row.IsNull("EmpId") && row["EmpId"]!=DBNull.Value)
                    {
                        item.EmpId = Convert.ToInt32(row["EmpId"]);
                    }
                    if (!row.IsNull("ExcId") && row["ExcId"] != DBNull.Value)
                    {
                        item.ExcId = Convert.ToInt32(row["ExcId"]);
                    }
                    
                    item.CustomField1 = String.Format("{0}", row["CustomField1"]);
                    item.CustomField2 = String.Format("{0}", row["CustomField2"]);
                    item.CustomField3 = String.Format("{0}", row["CustomField3"]);
                    item.CustomField4 = String.Format("{0}", row["CustomField4"]);
                    item.CustomField5 = String.Format("{0}", row["CustomField5"]);

                    list.Add(item);

                }
                dataTable.EndLoadData();
            }
            return list;
        }

        private List<DocumentDetails> GetListUpdate(DataTable dataTable)
        {
            List<DocumentDetails> list = new List<DocumentDetails>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    DocumentDetails item = new DocumentDetails();
                    item.DocDetId = Convert.ToInt32(row["DocDetId"]);
                    item.ConDetId = Convert.ToInt32(row["ConDetId"]);
                    item.DocDetContent = String.Format("{0}", row["DocDetContent"]);
                    if (!row.IsNull("EmpId") && row["EmpId"] != DBNull.Value)
                    {
                        item.EmpId = Convert.ToInt32(row["EmpId"]);
                    }
                    if (!row.IsNull("ExcId") && row["ExcId"] != DBNull.Value)
                    {
                        item.ExcId = Convert.ToInt32(row["ExcId"]);
                    }

                    item.CustomField1 = String.Format("{0}", row["CustomField1"]);
                    item.CustomField2 = String.Format("{0}", row["CustomField2"]);
                    item.CustomField3 = String.Format("{0}", row["CustomField3"]);
                    item.CustomField4 = String.Format("{0}", row["CustomField4"]);
                    item.CustomField5 = String.Format("{0}", row["CustomField5"]);

                    list.Add(item);

                }
                dataTable.EndLoadData();
            }
            return list;
        }

        private List<DocumentDetails> GetListDelete(DataTable dataTable)
        {
            List<DocumentDetails> list = new List<DocumentDetails>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    DocumentDetails item = new DocumentDetails();
                    item.DocDetId = Convert.ToInt32(row["DocDetId", DataRowVersion.Original]);
                    list.Add(item);

                }
                dataTable.EndLoadData();
            }
            return list;
        }

        #endregion

        #region "Background Worker"

        private void loadworker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                LstInsuranceType = ClsInsuranceType.SelectAll();
                LstDocumentTypes = ClsDocumentTypes.SelectAll();
                LstInvestors = ClsInvestors.SelectAll();
                e.Result = LstInsuranceType;
            }
            catch (Exception)
            {
                e.Cancel = true;
            }
        }

        private void loadworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Action a = LoadLookupData;
            txtInsTypId.Invoke(a);
            ClsVariable.SetWaitDialogCaption(string.Format("Danh sách {0} đã được nạp", Text));
        }
        #endregion

        #region "Form Event"
        private void FrmDocumentsDetailLoad(object sender, EventArgs e)
        {
            BlankForm();
            GetData();
            btnSaveNew.Enabled = !OnlyView;
            btnSave.Enabled = !OnlyView;
            btnSaveClose.Enabled = !OnlyView;
            btnDelete.Enabled = !OnlyView;
            btnDesign.Enabled = !OnlyView;
            if (!String.IsNullOrEmpty(FormXtraLayoutTemplate))
            {
                var fileLayout = ClsVariable.GetRestoreLayoutFullPath(FormXtraLayoutTemplate);
                layoutControl.RestoreLayoutFromXml(fileLayout);
            }
            if (!String.IsNullOrEmpty(FormXtraGridLayoutTemplate))
            {
                var filePath = ClsVariable.GetRestoreLayoutFullPath(FormXtraGridLayoutTemplate);
                grvDetail.RestoreLayoutFromXml(filePath, DevExpress.Utils.OptionsLayoutBase.FullLayout);
            }
        }
        #endregion

        #region "Toolbar Event"
        private void TbMenuItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "btnSave":
                    DoSave();
                    break;
                case "btnSaveNew"://Lưu và thêm mới
                    SaveNew = true;
                    DoSave();
                    break;
                case "btnSaveClose"://Lưu và đóng
                    SaveClose = true;
                    DoSave();
                    break;
                case "btnDelete":
                    DoDelete();
                    break;
                case "btnDesign":
                    ClsVariable.ShowDesignXtraGrid(grdDetail);
                    break;
                case "btnRefresh"://Nạp lại danh mục
                    break;
                case "btnHistory"://History
                    break;
                case "btnClose":
                    Close();
                    break;
            }
        }
        #endregion

        #region "Lookup Edit Event"
        private void txtConId_EditValueChanged(object sender, EventArgs e)
        {
            if (txtConId.EditValue != null)
            {
                int contId = Convert.ToInt32(txtConId.EditValue);
                GetContractInfor(contId);
            }
        }

        private void txtDocTypId_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            switch (e.Button.Caption)
            {
                case "btnAdd":
                    var item = ClsForms.SelectByFormClass("ContractManager.Lists.Forms.FrmDocumentTypes");
                    if (item == null) return;
                    var frm = new FrmDocumentTypeDetail
                        {
                        MasterId = 0,
                        AsSysBillStyleId = Convert.ToInt32(item.Form_SysBillStyleId),
                        AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                        AsPerPersonId = ClsVariable.EmployeeId,
                        FormNo = item.FormNo,
                        SaveFormMaster = true,
                        FormSysBillStyleIdExport = Convert.ToInt32(item.Form_SysBillStyleIdExport),
                        FormXtraLayoutTemplate = item.Form_XtraLayoutTemplate,
                        FormXtraGridLayoutTemplate = item.Form_XtraGridLayoutTemplate,
                        FormReportLayoutTemplate = item.Form_ReportLayoutTemplate,
                        FormDetailVatGridLayout = item.Form_DetailVatGridLayout,
                        VoucherCate = Convert.ToInt32(item.VoucherCate),
                        IsPrintAfterSave = Convert.ToBoolean(item.Form_IsPrintAfterSave),
                        FormAccountDefault = Convert.ToInt32(item.FormAccountDefault),
                        FormIsNotValidate = Convert.ToBoolean(item.FormIsNotValidate),
                        Text = String.Format("Thông tin {0}", item.Form_Name),

                        MdiParent = this.MdiParent,
                        WindowState = FormWindowState.Maximized
                    };
                    frm.Closed += FrmOnClosed;
                    frm.Show();

                    break;
            }
        }

        private void FrmOnClosed(object sender, EventArgs eventArgs)
        {
            var frmDocumentTypeDetail = sender as FrmDocumentTypeDetail;
            if (frmDocumentTypeDetail != null && frmDocumentTypeDetail.SaveClose)
            {
                if (frmDocumentTypeDetail.List != null)
                {
                    foreach (var lstItem in frmDocumentTypeDetail.List)
                    {
                        LstDocumentTypes.Add(lstItem);
                        txtDocTypId.Refresh();
                    }
                }
            }

            
        }

        #endregion

        #region "XtraGrid Event"
        private void grvDetail_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Value == null) return;
            var view = (GridView)sender;

            switch (e.Column.FieldName)
            {
                case "ConDetId"://Noi dung cong viec
                    int conDetId = Convert.ToInt32(e.Value);
                    var item = ClsContractDetails.SelectByPk(conDetId);
                    if (item != null)
                    {
                        view.SetRowCellValue(e.RowHandle, "ConDetAmount", item.ConDetAmount);
                        view.SetRowCellValue(e.RowHandle, "ConDetSetAmount", item.ConDetSetAmount);
                        view.SetRowCellValue(e.RowHandle, "ConDetStartDate", item.ConDetStartDate);
                        view.SetRowCellValue(e.RowHandle, "ConDetEndDate", item.ConDetEndDate);
                        view.SetRowCellValue(e.RowHandle, "ConDetPlanEndDate", item.ConDetPlanEndDate);
                        view.SetRowCellValue(e.RowHandle, "ConDetNumDay", item.ConDetNumDay);
                        if (item.MbID != null)
                        {
                            var mbItem = ClsMemberBranch.SelectByPk(Convert.ToInt32(item.MbID));
                            view.SetRowCellValue(e.RowHandle, "MbID", mbItem.MbName);
                        }
                        view.SetRowCellValue(e.RowHandle, "ConDetCtManager", item.ConDetCtManager);
                        view.SetRowCellValue(e.RowHandle, "ConDetLeader", item.ConDetLeader);
                        if (item.WorkId != null)
                        {
                            var wkItem = ClsWorkType.SelectByPk(Convert.ToInt32(item.WorkId));
                            view.SetRowCellValue(e.RowHandle, "WorkId", wkItem.WorkName);
                        }
                        view.SetRowCellValue(e.RowHandle, "ConDetDecisionNo", item.ConDetDecisionNo);
                        view.SetRowCellValue(e.RowHandle, "ConDetAllocationDecision", item.ConDetAllocationDecision);
                        view.SetRowCellValue(e.RowHandle, "ConDetInsRate", item.ConDetInsRate);
                        view.SetRowCellValue(e.RowHandle, "ConDetExcRate", item.ConDetExcRate);
                        view.SetRowCellValue(e.RowHandle, "ConDetInsAmount", item.ConDetInsAmount);
                        view.SetRowCellValue(e.RowHandle, "ConDetInsAfterAmount", item.ConDetInsAfterAmount);
                        view.SetRowCellValue(e.RowHandle, "ConDetExcAmount", item.ConDetExcAmount);
                    }
                    break;

            }
        }
        #endregion


    }
}
